package com.wzw.shortcuthelper.core.helper

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ShortcutManager
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import com.m4399.shortcut_test.ShortCutCreateUtil
import com.m4399.shortcut_test.broadcast.IntentSenderHelper
import com.m4399.shortcut_test.broadcast.ShortCurtCreateBroadcastReceiver
import com.m4399.shortcut_test.core.content.pm.ShortcutInfoCompat
import com.m4399.shortcut_test.core.content.pm.ShortcutManagerCompat
import com.m4399.shortcut_test.core.helper.ShortcutHelper


/**
 * Description: TODO.
 *
 * @author  wang.zhiwei
 * @date    2022年01月12日 11:16
 *
 * Copyright (c) 2022年, 4399 Network CO.ltd. All Rights Reserved.
 */
object CreateOrUpdateShortcut {
    private const val TAG = "shortCut"
    fun isShortcutExit(context: Context, id: String, label: String): Boolean {
        var exitForLower25 = false
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            val mShortcutManager = context.getSystemService(ShortcutManager::class.java)
                ?: return false
            val pinnedShortcuts = mShortcutManager.pinnedShortcuts
            for (pinnedShortcut in pinnedShortcuts) {
                if (pinnedShortcut.id == id) {
                    return true
                }
            }
        } else {
            val shortcutExitForCommon = isShortcutExistByThirdPart(context, label)
            Log.d(TAG, "isShortcutExit: 第三方桌面查询： $shortcutExitForCommon")
            return shortcutExitForCommon
        }

        if (!exitForLower25){
            exitForLower25 = isShortcutExistByThirdPart(context,label)
            Log.d(TAG, "isShortcutExit: 大于7.1的手机第三方桌面查询方式重试 $exitForLower25")
            return exitForLower25
        }

        return false

    }


    /**
     * 根据提供的api查询
     */
    private fun isShortcutExitByShortcutManager(context: Context, id: String, label: String):Boolean{
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            val mShortcutManager = context.getSystemService(ShortcutManager::class.java)
                ?: return false
            val pinnedShortcuts = mShortcutManager.pinnedShortcuts
            for (pinnedShortcut in pinnedShortcuts) {
                if (pinnedShortcut.id == id) {
                    return true
                }
            }
        }

        return false

    }
     fun isShortcutExistByThirdPart(context: Context?, title: String?): Boolean {
        var isInstallShortcut = false
        var authority = ""
        if (null == context || TextUtils.isEmpty(title)) return isInstallShortcut
        if (TextUtils.isEmpty(authority)) authority = getAuthorityFromPermission(context)
        val cr = context.contentResolver
        Log.d(TAG, "isShortCutExist: $authority")
        if (!TextUtils.isEmpty(authority)) {
            try {
                val uri = Uri.parse(authority)
                val c: Cursor? = cr.query(
                    uri,
                    arrayOf("title", "iconResource"),
                    "title=?",
                    arrayOf(title),
                    null
                )
                if (c != null && c.count > 0) {
                    isInstallShortcut = true
                }
                if (null != c && !c.isClosed) c.close()
            } catch (e: java.lang.Exception) {
                // TODO: handle exception
                Log.e("isShortCutExist", e.message!!)
            }
        }
        return isInstallShortcut
    }


    private fun getCurrentLauncherPackageName(context: Context): String {
        val intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_HOME)
        val res = context.packageManager.resolveActivity(intent, 0)
        if (res?.activityInfo == null) {
            // should not happen. A home is always installed, isn't it?
            return ""
        }
        return if (res.activityInfo.packageName == "android") {
            ""
        } else {
            res.activityInfo.packageName
        }
    }

    private fun getAuthorityFromPermissionDefault(context: Context): String? {
        return getThirdAuthorityFromPermission(
            context,
            "com.android.launcher.permission.READ_SETTINGS"
        )
    }

    private fun getThirdAuthorityFromPermission(context: Context, permission: String): String? {
        Log.d(TAG, "getThirdAuthorityFromPermission: permission $permission")
        if (TextUtils.isEmpty(permission)) {
            return ""
        }
        try {
            val packs = context.packageManager.getInstalledPackages(PackageManager.GET_PROVIDERS)
                ?: return ""
            for (pack in packs) {
                val providers = pack.providers
                if (providers != null) {
                    for (provider in providers) {
                        if (permission == provider.readPermission || permission == provider.writePermission) {
                            Log.d(
                                TAG,
                                "getThirdAuthorityFromPermission authority: ${provider.authority}"
                            )
                            if (!TextUtils.isEmpty(provider.authority) // 精准匹配launcher.settings，再一次验证
                                && (provider.authority.contains(".launcher.settings")||provider.authority.contains(
                                    ".launcher2.settings"
                                ))
                            ) return provider.authority
                        }
                    }
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return ""
    }

    fun getAuthorityFromPermission(context: Context): String {
        // 获取默认
        var authority = getAuthorityFromPermissionDefault(context)
        // 获取特殊第三方
        if (authority == null || authority.trim { it <= ' ' } == "") {
            var packageName = getCurrentLauncherPackageName(context)
            packageName += ".permission.READ_SETTINGS"
            authority = getThirdAuthorityFromPermission(context, packageName)
        }
        // 还是获取不到，直接写死
        if (TextUtils.isEmpty(authority)) {
            val sdkInt = Build.VERSION.SDK_INT
            authority = if (sdkInt < 8) { // Android 2.1.x(API 7)以及以下的
                "com.android.launcher.settings"
            } else if (sdkInt < 19) { // Android 4.4以下
                "com.android.launcher2.settings"
            } else { // 4.4以及以上
                "com.android.launcher3.settings"
            }
        }
        authority = "content://$authority/favorites?notify=true"
        return authority
    }

    fun createOrUpdateShortcut(context: Context, shortcutInfoCompat: ShortcutInfoCompat): Boolean {
        Log.d(TAG, "createOrUpdateShortcut: context $context")
        val shortcutExit = isShortcutExit(context, shortcutInfoCompat.id, shortcutInfoCompat.shortLabel.toString())
        if (shortcutExit) {
            Log.d(TAG, "createOrUpdateShortcut: 已存在快捷方式")
            Toast.makeText(context, "快捷方式已存在，不添加", Toast.LENGTH_SHORT).show()
            ShortCutCreateUtil.shortCutCreateCallback?.onAlreadyCreate()
        } else {
            Log.d(TAG, "createOrUpdateShortcut: 不存在准备添加")
            val bundle = Bundle()
            bundle.putString(ShortcutHelper.EXTRA_ID, shortcutInfoCompat.id)
            bundle.putString(ShortcutHelper.EXTRA_LABEL, shortcutInfoCompat.shortLabel.toString())
            val defaultIntentSender = IntentSenderHelper.getDefaultIntentSender(
                context, ShortcutHelper.BROADCAST_ACTION,
                ShortCurtCreateBroadcastReceiver::class.java, bundle

            )
            val requestPinShortcut = ShortcutManagerCompat.requestPinShortcut(
                context,
                shortcutInfoCompat,
                defaultIntentSender
            )
            Log.d(TAG, "createOrUpdateShortcut: 快捷方式添加 ${if (requestPinShortcut) "成功" else "失败"}")


            return requestPinShortcut
        }
        return false
    }

}